# -*- coding:utf-8 -*-

from app import db
from app.models.message import Message, MessageMiddle, FrontMessage
from app.models.account import Staff
import top.api
from task import cly
from config import Config
import datetime


config = Config()

def message(content, message_type, role_list=None, server_id=None):
    """
    :param content: 消息实体
    :param message_type: 消息类型 etc: u'贷款' u'审核' u'分单'
    :param role_list: 角色列表 etc: [u'admin', 'manage']
    :param server_id: 客服staff_number
    """
    m = Message(content=content, type=message_type)

    m.save()

    default_list = [u'admin']  # 默认给管理层发消息
    if role_list:  # 给部门发消息
        if u'admin' not in role_list:
            role_list.extend(default_list)
        for role in role_list:
            data = dict(
                message_id=m.id,
                role=role,
                type=message_type
            )
            db.session.add(MessageMiddle(**data))
        db.session.commit()

    if server_id:  # 给某个客服发消息
        data = dict(
            message_id=m.id,
            server_id=server_id,
            type=message_type
        )
        db.session.add(MessageMiddle(**data))
        db.session.commit()

def frontmessage(message_type, operation, user_id):
    data = {}
    data['content'] = operation
    data['user_id'] = user_id
    data['time'] = datetime.datetime.now()
    data['status'] = False
    data['message_type'] = message_type
    db.session.add(FrontMessage(**data))
    db.session.commit()
    return 0

@cly.task
def send_phone_msg(phone, msg, template_code):
	req = top.api.AlibabaAliqinFcSmsNumSendRequest()
	req.set_app_info(top.appinfo(config['ALIDAYU_APP_KEY'], config['ALIDAYU_SECRET_KEY']))
	req.extend = ""
	req.sms_type = config['ALIDAYU_SMSTYPE']
	req.sms_free_sign_name = config['ALIDAYU_SMSFREESIGNNAME']
	req.sms_param = msg
	req.rec_num = phone
	req.sms_template_code = template_code
		
	resp = req.getResponse()
	if 'error_response' in resp:
		if resp['error_response']['subcode'] == 'isv.BUSINESS_LIMIT_CONTROL':
			pass
